package com.qingcheng.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.qingcheng.util.IdWorker;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qingcheng.dao.OrderConfigMapper;
import com.qingcheng.dao.OrderItemMapper;
import com.qingcheng.dao.OrderLogMapper;
import com.qingcheng.dao.OrderMapper;
import com.qingcheng.entity.PageResult;
import com.qingcheng.pojo.order.*;
import com.qingcheng.service.goods.SkuService;
import com.qingcheng.service.order.CartService;
import com.qingcheng.service.order.OrderService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Service(interfaceClass = OrderService.class)
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderConfigMapper orderConfigMapper;

    @Autowired
    private CartService cartService;

    @Autowired
    private RabbitTemplate rabbitTemplate;





    /**
     * 返回全部记录
     *
     * @return
     */
    public List<Order> findAll() {
        return orderMapper.selectAll();
    }

    public IdWorker idWorker = new IdWorker();

    /**
     * 分页查询
     *
     * @param page 页码
     * @param size 每页记录数
     * @return 分页结果
     */
    public PageResult<Order> findPage(int page, int size) {
        PageHelper.startPage(page, size);
        Page<Order> orders = (Page<Order>) orderMapper.selectAll();
        return new PageResult<Order>(orders.getTotal(), orders.getResult());
    }

    /**
     * 条件查询
     *
     * @param searchMap 查询条件
     * @return
     */
    public List<Order> findList(Map<String, Object> searchMap) {
        Example example = createExample(searchMap);
        return orderMapper.selectByExample(example);
    }

    /**
     * 分页+条件查询
     *
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    public PageResult<Order> findPage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page, size);
        Example example = createExample(searchMap);
        Page<Order> orders = (Page<Order>) orderMapper.selectByExample(example);
        return new PageResult<Order>(orders.getTotal(), orders.getResult());
    }

    /**
     * 根据Id查询
     *
     * @param id
     * @return
     */
    public Order findById(String id) {
        return orderMapper.selectByPrimaryKey(id);
    }



    @Reference
    private SkuService skuService;
    /**
     * 新增
     * 根据购物车信息在主订单中新增订单信息，
     *
     * @param order
     */
    public Map<String,Object> add(Order order) {
        //根据用户信息获取更新后的购物车列表
        List<Map<String, Object>> orderItemList = cartService.findNewOrderItemList(order.getUsername());
        //获取选中的购物车----使用Stream流进行过滤，获取key为item的数据封装成Map*/
        List<OrderItem> orderItems = orderItemList.stream()
                .filter(cart -> (boolean) cart.get("checked"))
                .map(cart -> (OrderItem) cart.get("item"))
                .collect(Collectors.toList());
        //扣减库存,如果库存及销量数据没有发生变化
        if (!skuService.deductionStock(orderItems)){
            throw new RuntimeException("库存扣减失败");
        }
        try {
            //保存订单主表---tb_order
            order.setId(idWorker.nextId()+"");//雪花算法生成id
            // TODO Stream流 合计数计算
            IntStream numStream = orderItems.stream().mapToInt(OrderItem::getNum);
            IntStream moneyStream = orderItems.stream().mapToInt(OrderItem::getMoney);
            int totalNum = numStream.sum();//总数量
            int totalMoney = moneyStream.sum();//总金额
            //根据订单用户计算优惠金额
            int preMoney = cartService.preferential(order.getUsername());
            order.setTotalNum(totalNum);
            order.setTotalMoney(totalMoney);
            order.setPreMoney(preMoney);
            order.setPayMoney(totalMoney-preMoney);//实际支付金额
            order.setCreateTime(new Date());
            order.setUpdateTime(new Date());
            order.setPayStatus("0");
            order.setConsignStatus("0");
            order.setOrderStatus("0");
            orderMapper.insert(order);
            rabbitTemplate.convertAndSend("","queue.ordercreate",JSON.toJSONString(order));

            double proportion = (double) order.getPayMoney()/totalMoney;

            //保存订单明细---tb_order_item,
            //过滤后的购物车
            for (OrderItem orderItem : orderItems) {
                orderItem.setOrderId(order.getId());//订单详表设置订单主表Id
                orderItem.setId(idWorker.nextId()+"");
                orderItem.setPayMoney((int)(orderItem.getMoney()*proportion));//支付金额
                orderItemMapper.insert(orderItem);
            }
        }catch (Exception e){
            rabbitTemplate.convertAndSend("","queue.skuback", JSON.toJSONString(orderItems));
            throw new RuntimeException("订单生成失败");

        }

        //清除选中的购物车
        cartService.deleteCheckedCart(order.getUsername());
        //返回订单号和支付的金额
        Map<String,Object> map = new HashMap<>();
        map.put("ordersn",order.getId());
        map.put("money",order.getPayMoney());
        return map;
    }

    /**
     * 修改
     *
     * @param order
     */
    public void update(Order order) {
        orderMapper.updateByPrimaryKeySelective(order);
    }

    /**
     * 删除
     *
     * @param id
     */
    public void delete(String id) {
        orderMapper.deleteByPrimaryKey(id);
    }


    /**
     * 查询组合订单列表
     *
     * @param order_item
     */
    public void findOrder_Item(Order_Item order_item) {
        // TODO

    }

    @Autowired
    private OrderItemMapper orderItemMapper;

    /**
     * 查询组合订单
     *
     * @param id
     * @return
     */
    @Transactional
    public Order_Item findOrder(String id) {

        Order_Item orderItem = new Order_Item();
        Example example = new Example(OrderItem.class);
        Example.Criteria criteria = example.createCriteria();

        Order order = orderMapper.selectByPrimaryKey(id);
        orderItem.setOrder(order);
        String oid = order.getId();
        criteria.andEqualTo("orderId", oid);
        OrderItem item = orderItemMapper.selectOneByExample(example);
        orderItem.setOrderItem(item);

        return orderItem;
    }

    /**
     * 批量发货
     *
     * @param orders
     */
    @Autowired
    private OrderLogMapper orderLogMapper;

    @Transactional
    public void batchSend(List<Order> orders) {
        //判断运单号和物流公司是否为空
        for (Order order : orders) {
            if (order.getShippingCode() == null || order.getShippingName() == null) {
                throw new RuntimeException("请选择快递公司和填写快递单号");
            }
        }
        //循环发货
        Example example = new Example(OrderLog.class);
        Example.Criteria criteria = example.createCriteria();

        for (Order order : orders) {
            order.setOrderStatus("3");//订单状态
            order.setConsignStatus("2");//发货状态
            order.setConsignTime(new Date());//发货时间
            orderMapper.updateByPrimaryKeySelective(order);
            criteria.andEqualTo("orderId", order.getId());
            List<OrderLog> orderLogs = orderLogMapper.selectByExample(example);

            IdWorker idWorker = new IdWorker();
            // TODO 记录订单日志
            OrderLog orderLog = new OrderLog();
            orderLog.setId(idWorker.nextId() + "");
            orderLog.setOperater("system");
            orderLog.setOperateTime(new Date());
            orderLog.setOrderId(order.getId());
            order.setOrderStatus("1");
            orderLog.setPayStatus("1");
            orderLog.setRemarks("支付流水号为： 待完成");
            if (orderLogs.size() == 0) {
                orderLogMapper.insert(orderLog);
            } else {
                orderLogMapper.updateByPrimaryKeySelective(orderLog);
            }
        }
    }


    /**
     * 超时
     */
    public void orderTimeOutLog() {
        //订单超时未付款 自动关闭
        //查询超时时间
        OrderConfig orderConfig = orderConfigMapper.selectByPrimaryKey(1);
        Integer orderTimeOut = orderConfig.getOrderTimeout();//超时时间

        //得到超时时间点
        LocalDateTime localDateTime = LocalDateTime.now().minusMinutes(orderTimeOut);

        //设置查询条件
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andLessThan("createTime", localDateTime);//创建时间小于超时时间
        criteria.andEqualTo("orderStatus", "0");//未付款
        criteria.andEqualTo("isDelete", "0");//未页面删除

        //查询超时订单
        List<Order> orders = orderMapper.selectByExample(example);
        for (Order order : orders) {
            //记录订单变动日志
            OrderLog orderLog = new OrderLog();
            orderLog.setOperater("system");
            orderLog.setOperateTime(new Date());
            orderLog.setOrderStatus("4");
            orderLog.setPayStatus(order.getPayStatus());
            orderLog.setConsignStatus(order.getConsignStatus());
            orderLog.setRemarks("超时订单，系统自动关闭");
            orderLog.setOrderId(order.getId());
            orderLogMapper.insert(orderLog);

            //更新订单状态
            order.setOrderStatus("4");
            order.setCloseTime(new Date());//关闭日期
            orderMapper.updateByPrimaryKeySelective(order);

        }
    }


    /**
     * 合并订单
     *
     * @param masterOrderId
     * @param slaveOrderId
     */
    @Transactional
    public void merge(String masterOrderId, String slaveOrderId) {


        Order order = orderMapper.selectByPrimaryKey(masterOrderId);
        Order order2 = orderMapper.selectByPrimaryKey(slaveOrderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        if (order2 == null) {
            throw new RuntimeException("订单不存在");

        }
        String order1Username = order.getUsername();
        String order2Username = order2.getUsername();
        if (!order1Username.equals(order2Username)) {
            throw new RuntimeException("合并订单不属于同一用户");
        }
        order.setTotalMoney(order.getTotalMoney() + order2.getTotalMoney());
        order.setTotalNum(order.getTotalNum() + order2.getTotalNum());
        order.setPostFee(order2.getPostFee() + order.getPostFee());
        order.setPayMoney(order2.getPayMoney() + order.getPayMoney());
        order.setUpdateTime(new Date());
        orderMapper.updateByPrimaryKeySelective(order);

        //逻辑删除从订单
        Order updateOrder = new Order();

        updateOrder.setIsDelete("1");
        updateOrder.setId(slaveOrderId);
        orderMapper.updateByPrimaryKeySelective(updateOrder);


        //从订单的订单明细归属于主订单
        Example example = new Example(OrderItem.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderId", slaveOrderId);
        OrderItem orderItem = new OrderItem();
        orderItem.setOrderId(masterOrderId);
        orderItemMapper.updateByExampleSelective(orderItem, example);

        // TODO 更新日志
        OrderLog log1 = new OrderLog();
        log1.setId(idWorker.nextId() + "");
        log1.setOperater("system");
        log1.setOperateTime(new Date());
        log1.setOrderStatus("1");
        log1.setPayStatus("1");
        if (masterOrderId != null && !"".equals(masterOrderId)) {
            log1.setOrderId(masterOrderId);
        }
        log1.setRemarks("当前主订单：" + masterOrderId + "合并了从订单：" + slaveOrderId);
        orderLogMapper.insert(log1);


        OrderLog log2 = new OrderLog();
        log2.setId(idWorker.nextId() + "");
        log2.setOperater("system");
        log2.setOperateTime(new Date());
        log2.setOrderStatus("1");
        log2.setPayStatus("1");
        if (slaveOrderId != null && !"".equals(slaveOrderId)) {
            log2.setOrderId(slaveOrderId);
        }
        log1.setRemarks("当前从订单：" + slaveOrderId + "被主订单：" + masterOrderId + "合并了");


    }


    /**
     * 拆分订单
     *
     * @param orderItems
     * @param orderId
     */


    // TODO 逻辑思路
    @Transactional
    //拆分订单，回显数据
    public void split(List<OrderItem> orderItems, String orderId) {
        //生成新订单
        Order newOrder = new Order();
        Order oldOrder = orderMapper.selectByPrimaryKey(orderId);
        if (oldOrder == null) {
            throw new RuntimeException("订单不存在");
        }
        BeanUtils.copyProperties(oldOrder, newOrder); //将旧订单的信息复制到新的订单
        Date date = new Date();
        newOrder.setTotalNum(0);
        newOrder.setTotalMoney(0);
        newOrder.setPayMoney(0);
        newOrder.setPostFee(0);
        newOrder.setId(idWorker.nextId() + "");
        newOrder.setCreateTime(date);
        newOrder.setUpdateTime(date);


        oldOrder.setTotalNum(0);
        oldOrder.setTotalMoney(0);
        oldOrder.setPayMoney(0);
        oldOrder.setPostFee(0);
        oldOrder.setPayMoney(0);

        for (OrderItem orderItem : orderItems) {
            OrderItem entireOrderItem = orderItemMapper.selectByPrimaryKey(orderItem.getId());
            int splitNum = orderItem.getNum(); //切分数量
            Integer entireNum = entireOrderItem.getNum();//订单存量
            if (splitNum > entireNum) {
                throw new RuntimeException("拆分数量不合理");
            } else if (splitNum < 0) {
                throw new RuntimeException("拆分数量不合理");
            } else {
                newOrder.setTotalNum(newOrder.getTotalNum() + splitNum);
                newOrder.setTotalMoney(newOrder.getTotalMoney() + entireOrderItem.getMoney() * splitNum / entireNum);
                newOrder.setPreMoney(newOrder.getPreMoney() + (entireOrderItem.getMoney() - entireOrderItem.getPayMoney() * splitNum));
                newOrder.setPostFee(newOrder.getPostFee() + entireOrderItem.getPostFee() * splitNum / entireNum);
                newOrder.setPayMoney(newOrder.getPayMoney() + entireOrderItem.getPayMoney() * splitNum / entireNum);

                // 通过减法处理，不通过比例，保证相加后完全等于原订单统计数值
                oldOrder.setTotalNum(oldOrder.getTotalNum() - splitNum);
                oldOrder.setTotalMoney(oldOrder.getTotalMoney() -
                        (entireOrderItem.getMoney() - entireOrderItem.getMoney() * splitNum / entireNum));
                oldOrder.setPreMoney(oldOrder.getPreMoney() -
                        ((entireOrderItem.getMoney() - entireOrderItem.getPayMoney()) - (entireOrderItem.getMoney() - entireOrderItem.getPayMoney()) * splitNum / entireNum));
                oldOrder.setPostFee(oldOrder.getPostFee() -
                        (entireOrderItem.getPostFee() - entireOrderItem.getPostFee() * splitNum / entireNum));// 设想邮费完全按切分比例计算
                oldOrder.setPayMoney(oldOrder.getPayMoney() -
                        (entireOrderItem.getPayMoney() - entireOrderItem.getPayMoney() * splitNum / entireNum));


                //处理订单明细
                if (splitNum == entireNum) {

                    //切分数量等于明细数量，将该订单明细绑定的订单号全部从旧订单更新到新订单
                    OrderItem updateOrderItem = new OrderItem();
                    updateOrderItem.setOrderId(newOrder.getId());//订单明细绑定的订单号
                    updateOrderItem.setId(orderItem.getId());
                    orderItemMapper.updateByPrimaryKeySelective(updateOrderItem);
                } else {
                    //生成切分的新订单明细
                    OrderItem newOrderItem = new OrderItem();
                    BeanUtils.copyProperties(entireOrderItem, newOrderItem);
                    newOrderItem.setId(idWorker.nextId() + "");
                    newOrderItem.setOrderId(newOrder.getId());
                    newOrderItem.setNum(splitNum);
                    newOrderItem.setMoney(entireOrderItem.getMoney() * splitNum / entireNum);
                    newOrderItem.setPayMoney(entireOrderItem.getPayMoney() * splitNum / entireNum);
                    newOrderItem.setWeight(entireOrderItem.getWeight() * splitNum / entireNum);
                    newOrderItem.setPostFee(entireOrderItem.getPostFee() * splitNum / entireNum);
                    orderItemMapper.insert(newOrderItem);

                    // 更新旧订单明细统计数据
                    entireOrderItem.setNum(entireOrderItem.getNum() - newOrderItem.getNum());
                    entireOrderItem.setMoney(entireOrderItem.getMoney() - newOrderItem.getMoney());
                    entireOrderItem.setPayMoney(entireOrderItem.getPayMoney() - newOrderItem.getPayMoney());
                    entireOrderItem.setWeight(entireOrderItem.getWeight() - newOrderItem.getWeight());
                    entireOrderItem.setPostFee(entireOrderItem.getPostFee() - newOrderItem.getPostFee());
                    orderItemMapper.updateByPrimaryKey(entireOrderItem);
                }
            }
        }

        //迭代统计完成之后
        orderMapper.insert(newOrder);
        orderMapper.updateByPrimaryKeySelective(oldOrder);

        //订单日志
        OrderLog oldOrderLog = new OrderLog();
        oldOrderLog.setId(idWorker.nextId() + "");
        oldOrderLog.setOperater("system");
        oldOrderLog.setOperateTime(date);
        if (oldOrder.getId() != null && !"".equals(oldOrder.getId())) {
            oldOrderLog.setOrderId(oldOrder.getId());
        }
        oldOrderLog.setOrderStatus(oldOrder.getOrderStatus());
        oldOrderLog.setPayStatus(oldOrder.getPayStatus());
        oldOrderLog.setConsignStatus(oldOrder.getConsignStatus());
        oldOrderLog.setRemarks("订单被拆分");
        orderLogMapper.insert(oldOrderLog);

        //拆分出新订单日志
        OrderLog newOrderLog = new OrderLog();
        newOrderLog.setId(idWorker.nextId() + "");
        newOrderLog.setOperater("system");
        newOrderLog.setOperateTime(date);
        if (newOrder.getId() != null && !"".equals(newOrder.getId())) {
            newOrderLog.setOrderId(newOrder.getId());
        }
        newOrderLog.setOrderStatus(newOrder.getOrderStatus());
        newOrderLog.setPayStatus(newOrder.getPayStatus());
        newOrderLog.setConsignStatus(newOrder.getConsignStatus());
        newOrderLog.setRemarks("差分出的新订单");
        orderLogMapper.insert(newOrderLog);

    }



    @Override
    public void updatePayStatus(String orderId, String transactionId) {
        //查询订单
        Order order = orderMapper.selectByPrimaryKey(orderId);
        if (order!=null&&"0".equals(order.getPayStatus())){
            //修改订单状态信息
            order.setPayStatus("1");
            order.setOrderStatus("1");
            order.setUpdateTime(new Date());
            order.setPayTime(new Date());
            order.setTransactionId(transactionId);//交易流水号
            orderMapper.updateByPrimaryKeySelective(order);


            //记录订单日志----tb_order_log
            OrderLog orderLog = new OrderLog();
            orderLog.setId(idWorker.nextId()+"");
            orderLog.setOperater("system");
            orderLog.setOperateTime(new Date());//操作时间
            orderLog.setOrderStatus("1");//订单状态
            orderLog.setPayStatus("1");//支付状态
            orderLog.setRemarks("支付流水号："+ transactionId);//备注
            orderLog.setOrderId(orderId);
            orderLogMapper.insert(orderLog);

        }

    }


    /**
     * 构建查询条件
     *
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap) {
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        if (searchMap != null) {
            // 订单id
            if (searchMap.get("id") != null && !"".equals(searchMap.get("id"))) {
                criteria.andLike("id", "%" + searchMap.get("id") + "%");
            }
            // 支付类型，1、在线支付、0 货到付款
            if (searchMap.get("payType") != null && !"".equals(searchMap.get("payType"))) {
                criteria.andLike("payType", "%" + searchMap.get("payType") + "%");
            }
            // 物流名称
            if (searchMap.get("shippingName") != null && !"".equals(searchMap.get("shippingName"))) {
                criteria.andLike("shippingName", "%" + searchMap.get("shippingName") + "%");
            }
            // 物流单号
            if (searchMap.get("shippingCode") != null && !"".equals(searchMap.get("shippingCode"))) {
                criteria.andLike("shippingCode", "%" + searchMap.get("shippingCode") + "%");
            }
            // 用户名称
            if (searchMap.get("username") != null && !"".equals(searchMap.get("username"))) {
                criteria.andLike("username", "%" + searchMap.get("username") + "%");
            }
            // 买家留言
            if (searchMap.get("buyerMessage") != null && !"".equals(searchMap.get("buyerMessage"))) {
                criteria.andLike("buyerMessage", "%" + searchMap.get("buyerMessage") + "%");
            }
            // 是否评价
            if (searchMap.get("buyerRate") != null && !"".equals(searchMap.get("buyerRate"))) {
                criteria.andLike("buyerRate", "%" + searchMap.get("buyerRate") + "%");
            }
            // 收货人
            if (searchMap.get("receiverContact") != null && !"".equals(searchMap.get("receiverContact"))) {
                criteria.andLike("receiverContact", "%" + searchMap.get("receiverContact") + "%");
            }
            // 收货人手机
            if (searchMap.get("receiverMobile") != null && !"".equals(searchMap.get("receiverMobile"))) {
                criteria.andLike("receiverMobile", "%" + searchMap.get("receiverMobile") + "%");
            }
            // 收货人地址
            if (searchMap.get("receiverAddress") != null && !"".equals(searchMap.get("receiverAddress"))) {
                criteria.andLike("receiverAddress", "%" + searchMap.get("receiverAddress") + "%");
            }
            // 订单来源：1:web，2：app，3：微信公众号，4：微信小程序  5 H5手机页面
            if (searchMap.get("sourceType") != null && !"".equals(searchMap.get("sourceType"))) {
                criteria.andLike("sourceType", "%" + searchMap.get("sourceType") + "%");
            }
            // 交易流水号
            if (searchMap.get("transactionId") != null && !"".equals(searchMap.get("transactionId"))) {
                criteria.andLike("transactionId", "%" + searchMap.get("transactionId") + "%");
            }
            // 订单状态
            if (searchMap.get("orderStatus") != null && !"".equals(searchMap.get("orderStatus"))) {
                criteria.andLike("orderStatus", "%" + searchMap.get("orderStatus") + "%");
            }
            // 支付状态
            if (searchMap.get("payStatus") != null && !"".equals(searchMap.get("payStatus"))) {
                criteria.andLike("payStatus", "%" + searchMap.get("payStatus") + "%");
            }
            // 发货状态
            if (searchMap.get("consignStatus") != null && !"".equals(searchMap.get("consignStatus"))) {
                criteria.andLike("consignStatus", "%" + searchMap.get("consignStatus") + "%");
            }
            // 是否删除
            if (searchMap.get("isDelete") != null && !"".equals(searchMap.get("isDelete"))) {
                criteria.andLike("isDelete", "%" + searchMap.get("isDelete") + "%");
            }

            // 数量合计
            if (searchMap.get("totalNum") != null) {
                criteria.andEqualTo("totalNum", searchMap.get("totalNum"));
            }
            // 金额合计
            if (searchMap.get("totalMoney") != null) {
                criteria.andEqualTo("totalMoney", searchMap.get("totalMoney"));
            }
            // 优惠金额
            if (searchMap.get("preMoney") != null) {
                criteria.andEqualTo("preMoney", searchMap.get("preMoney"));
            }
            // 邮费
            if (searchMap.get("postFee") != null) {
                criteria.andEqualTo("postFee", searchMap.get("postFee"));
            }
            // 实付金额
            if (searchMap.get("payMoney") != null) {
                criteria.andEqualTo("payMoney", searchMap.get("payMoney"));
            }


            if (searchMap.get("ids") != null) {
                // criteria.andIn("id", Arrays.asList((String[])searchMap.get("ids")));//转成String类型
                criteria.andIn("id", (List<String>) searchMap.get("ids"));//
                /**
                 *
                 * Arrays 和 List共同继承Collection 简化转化过程
                 *
                 **/
            }

        }
        return example;
    }

}
